package com.org.oracle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.org.oracle.mysql.entity.UserAnswerDetail;
import com.org.oracle.mapper.UserAnswerDetailsMapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.org.oracle.service.UserAnswerDetailsService;

import java.util.Calendar;
import java.util.Date;

/**
 * (UserAnswerDetails)表服务实现类
 *
 * @author luo
 * @since 2024-12-16 20:35:17
 */
@Service("userAnswerDetailsService")
public class UserAnswerDetailsServiceImpl extends ServiceImpl<UserAnswerDetailsMapper, UserAnswerDetail> implements UserAnswerDetailsService {

    @Resource
    private UserAnswerDetailsMapper userAnswerDetailMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public Integer countQuestionsByUid(String uid) {
        // 获取当前时间
        Date now = new Date();

        // 获取今天零点的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        Date startOfDay = calendar.getTime(); // 今天零点的时间

        // 创建查询条件对象
        QueryWrapper<UserAnswerDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid)
                // created_at 字段大于等于今天零点
                .ge("created_at", startOfDay)
                // created_at 字段小于当前时间
                .lt("created_at", now).eq("is_temporary", 0);
        int countFromDb = Math.toIntExact(userAnswerDetailMapper.selectCount(queryWrapper));
        // 从 Redis 中获取当天暂存题目数量（之前在暂存时记录的当天暂存题目数）
        String todayTemporaryCountKey = "today_temporary_count:" + uid;
        Object countObj = redisTemplate.opsForValue().get(todayTemporaryCountKey);
        Long todayTemporaryCount = 0L;
        if (countObj instanceof Number) {
            todayTemporaryCount = ((Number) countObj).longValue();
        }
        // 执行查询并返回计数
        return countFromDb + todayTemporaryCount.intValue();
    }
}

